package org.amphiprion.gameengine.font;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import org.amphiprion.diceroller.ApplicationConstants;

import android.util.Log;

public class Font {
	private HashMap<Integer, CharacterDescription> characters = new HashMap<Integer, CharacterDescription>();
	public String uri;
	public int coordWith;
	public int coordHeight;
	public int lineHeight;

	public Font(String fontFile, String bitmapFile) {
		this.uri = bitmapFile;

		try {
			InputStream is = Font.class.getResourceAsStream(fontFile);
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line;
			while ((line = br.readLine()) != null) {
				if (line.startsWith("char id=")) {
					String[] lineData = line.split("[=\\s]+"); // split on "=" and " "
					CharacterDescription c = new CharacterDescription(Integer.parseInt(lineData[2]));
					c.x = Integer.parseInt(lineData[4]);
					c.y = Integer.parseInt(lineData[6]);
					c.width = Integer.parseInt(lineData[8]);
					c.height = Integer.parseInt(lineData[10]);
					c.xOffset = Integer.parseInt(lineData[12]);
					c.yOffset = Integer.parseInt(lineData[14]);
					c.xAdvance = Integer.parseInt(lineData[16]);

					characters.put(c.ascii, c);
				} else if (line.startsWith("common lineHeight=")) {
					String[] lineData = line.split("[=\\s]+"); // split on "=" and " "
					lineHeight = Integer.parseInt(lineData[2]);

					int contentWidth = Integer.parseInt(lineData[6]);
					int mStrikeWidth = 1;
					while (mStrikeWidth < contentWidth) {
						mStrikeWidth <<= 1;
					}
					coordWith = mStrikeWidth;

					int contentHeight = Integer.parseInt(lineData[8]);
					int mStrikeHeight = 1;
					while (mStrikeHeight < contentHeight) {
						mStrikeHeight <<= 1;
					}
					coordHeight = mStrikeHeight;
				}
			}
			br.close();
			isr.close();
			is.close();

		} catch (Exception e) {
			Log.e(ApplicationConstants.PACKAGE, "", e);
		}
	}

	public CharacterDescription getCharacter(int ascii) {
		if (characters.containsKey(ascii)) {
			return characters.get(ascii);
		} else {
			return characters.get(32);
		}
	}

	public int getTotalAdvanceWidth(String text) {
		if (text == null) {
			return 0;
		}
		int w = 0;
		CharacterDescription cDesc;
		for (int i = 0; i < text.length(); i++) {
			char c = text.charAt(i);
			int asci = c;
			cDesc = getCharacter(asci);
			w += cDesc.xAdvance;
		}
		return w;
	}
}
